package br.com.cintiamuneerah.dao;



import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import br.com.cintiamuneerah.util.HibernateUtil;

@Component
public class SuperDao {
	
	private EntityManager entityManager;

	public <T> T buscarPorId(Class<T> classe, Long id) {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		return entityManager.find(classe, id);
	}

	public <T> void salvar(T entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.persist(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public <T> void deletar(T entity) {

		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.remove(entity);
			entityManager.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		}
	}

	public  <T> void alterar(T entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		}
	}
	
	public  <T> List<T> buscarTodos(Class<T> classe) {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		Query query = entityManager.createQuery("FROM " + classe);
		return query.getResultList();
	}
	
	public <T> List<T> executeQuery(String query) {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		return entityManager.createQuery(query).getResultList();
	}

}
